<script setup lang="ts">
import KnowledgeCard from './KnowledgeCard.vue'
import type { KnowledgeType, Knowledge } from '@/types/consult'
import { ref } from 'vue'
import { getKnowledgeListService } from '@/api/consult'
const props = defineProps<{
  type: KnowledgeType
}>()

const params = ref({
  type: props.type,
  pageSize: 10,
  current: 1,
})
const list = ref([] as Knowledge[])
const getKnowledgeList = async () => {
  try {
    loading.value = true
    const { pageTotal, total, rows } = await getKnowledgeListService(params.value)
    list.value = [...list.value, ...rows]
    if (params.value.current >= pageTotal) {
      finished.value = true // 没有更多数据了,加载结束
    }
    loading.value = false
    params.value.current++
    // 由于接口数据第三页有异常，所以直接跳过第三页
    params.value.current === 3 && params.value.current++
  } catch (error) {
    console.log(error)
  }
}
const loading = ref(false)
const finished = ref(false)

// 上拉加载更多
const onLoad = () => {
  getKnowledgeList()
}

// 下拉刷新
const onRefresh = async () => {
  if (finished.value) {
    params.value.current = 1
  }
  //   跳过第三页
  params.value.current === 3 && params.value.current++
  list.value = []
  finished.value = false
  const { pageTotal, total, rows } = await getKnowledgeListService(params.value)
  list.value = rows
  params.value.current++
  if (params.value.current > pageTotal) {
    params.value.current = 1
    finished.value = true // 没有更多数据了
  }
  loading.value = false
}
</script>

<template>
  <div class="knowledge-list">
    <van-pull-refresh v-model="loading" @refresh="onRefresh">
      <van-list
        v-model:loading="loading"
        :finished="finished"
        finished-text="没有更多了亲~"
        @load="onLoad"
      >
        <knowledge-card v-for="i in list" :key="i.id" :item="i"></knowledge-card>
      </van-list>
    </van-pull-refresh>
  </div>
</template>

<style lang="scss" scoped>
.knowledge-list {
  padding: 0 15px;
}
</style>
